﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using DatabaseAccess;
using System.Data;
using System.Text;
using System.Net.Mail;
using Liguo.AppCode;

namespace Liguo.Store
{
    public partial class Order : System.Web.UI.Page
    {
        int userId;
        int radioId = 0;
        //int[] amount;//数量
        //float[] weight;//重量
        string[] type;
        string[] price;
        double totalprice = 0;
        int flag = 0;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["User"] == null)
            {
                Response.Redirect("Port.aspx");
            }
            else
            {
                //获得用户信息
                User user = (User)Session["User"];
                //获得UserID
                userId = user.UserID;
                //userId = 140;
                int addressNum;
                if (!IsPostBack)
                {
                    SqlIt sql = new SqlIt();
                    DataSet ds = sql.SpecialItem("DeliveryInfo", "UserID =" + userId, "*");
                    addressNum = ds.Tables[0].Rows.Count;


                    String[] address = new String[addressNum];//收货人地址
                    String[] name = new string[addressNum];//收货人姓名
                    String[] phoneNum = new string[addressNum];//收获人电话
                    string[] detailAddr = new string[addressNum];//详细地址

                    for (int i = 0; i < addressNum; i++)
                    {
                        RadioButton rb = new RadioButton();
                        rb.GroupName = "single";
                        rb.ID = "selectRb" + i;
                        rb.CheckedChanged += new EventHandler(r_CheckedChanged);

                        Button changeButton = new Button();
                        changeButton.Text = "修改当前地址";
                        changeButton.ID = "changeButton" + i;
                        changeButton.BorderStyle = BorderStyle.None;
                        changeButton.BackColor = System.Drawing.Color.White;
                        changeButton.Attributes["class"] = "lbutton";
                        //changeButton.ForeColor = System.Drawing.Color.White;
                        //changeButton.UseSubmitBehavior = false;
                        changeButton.OnClientClick = "return fund(" + i + ")";

                        address[i] = ds.Tables[0].Rows[i]["Address"].ToString();
                        String _addr = (sql.SingleSpecialItem("AddressInfo", "ID = " + address[i], "Area")).ToString();
                        name[i] = ds.Tables[0].Rows[i]["CustomerName"].ToString();
                        phoneNum[i] = ds.Tables[0].Rows[i]["Tel"].ToString();
                        detailAddr[i] = ds.Tables[0].Rows[i]["DetailAddr"].ToString();

                        HiddenField hfName = new HiddenField();
                        hfName.ID = "name" + i;
                        hfName.Value = name[i];

                        HiddenField hfAddress = new HiddenField();
                        hfAddress.ID = "address" + i;
                        hfAddress.Value = address[i];

                        HiddenField hfPhone = new HiddenField();
                        hfPhone.ID = "phone" + i;
                        hfPhone.Value = phoneNum[i];

                        HiddenField hfDetail = new HiddenField();
                        hfDetail.ID = "detail" + i;
                        hfDetail.Value = detailAddr[i];

                        
                        HtmlTableRow Row = new HtmlTableRow();//创建行
                        Row.Attributes["class"] = "addr_style";
                        HtmlTableCell radio = new HtmlTableCell(); //创建单元格对象
                        radio.Controls.Add(rb);
                        HtmlTableCell text = new HtmlTableCell(); //创建单元格对象
                        text.Attributes["class"] = "addr_style";
                        text.Controls.Add(new LiteralControl(_addr + "(  " + name[i] + "    收  )  联系电话：" + phoneNum[i]));
                        HtmlTableCell changeAddr = new HtmlTableCell();//创建单元格对象
                        changeAddr.Controls.Add(changeButton);

                        HtmlTableCell hfn = new HtmlTableCell();
                        hfn.Controls.Add(hfName);
                        //HtmlTableCell hfp = new HtmlTableCell();
                        hfn.Controls.Add(hfPhone);
                        //HtmlTableCell hfa = new HtmlTableCell();
                        hfn.Controls.Add(hfAddress);
                        hfn.Controls.Add(hfDetail);


                        Row.Cells.Add(radio);
                        Row.Cells.Add(text);
                        Row.Cells.Add(changeAddr);
                        Row.Cells.Add(hfn);


                        addressTable.Rows.Add(Row);

                    }

                    //是时候显示商品了，
                    show();
                    //ds = sql.SpecialItem("CartInfo", "UserID =" + userId, "*");
                    //int goodsNum = ds.Tables[0].Rows.Count;

                    //String[] imagePath = new string[goodsNum];//图片路径
                    //String[] goodsName = new string[goodsNum];//商品名
                    //price = new string[goodsNum];//单价
                    //type = new string[goodsNum];
                    //amount = new int[goodsNum];//数量
                    //weight = new float[goodsNum];//重量
                    //DataSet cart = sql.SpecialItem("CartInfo", "UserID=" + userId, *);

                    //    for (int i = 0; i < goodsNum; i++)
                    //    {
                    //        string goodsID = ds.Tables[0].Rows[i]["GoodsID"].ToString();
                    //        DataSet dsss = sql.SpecialItem("GoodsInfo", "ID=" + goodsID, "*");//取商品信息表
                    //        goodsName[i] = dsss.Tables[0].Rows[0]["GoodsName"].ToString();//商品名
                    //        price[i] = dsss.Tables[0].Rows[0]["Price"].ToString();//商品价格
                    //        imagePath[i] = dsss.Tables[0].Rows[0]["PicturePath"].ToString();//商品图片路径
                    //        type[i] = dsss.Tables[0].Rows[0]["SaleMethod"].ToString();//商品类型
                    //        float priceTotal;
                    //        HtmlTableRow Row = new HtmlTableRow();//新增行
                    //        HtmlTableCell nameInTable = new HtmlTableCell(); //创建单元格对象
                    //        nameInTable.Controls.Add(new LiteralControl(goodsName[i]));
                    //        HtmlTableCell priceInTable = new HtmlTableCell();//创建单元格对象
                    //        priceInTable.Controls.Add(new LiteralControl(price[i]));
                    //        HtmlTableCell numberInTable = new HtmlTableCell();
                    //        Row.Cells.Add(nameInTable);
                    //        Row.Cells.Add(priceInTable);
                    //        if (type.Equals("0"))
                    //        {
                    //            amount[i] = Convert.ToInt32(ds.Tables[0].Rows[i]["Amount"].ToString());
                    //            numberInTable.Controls.Add(new LiteralControl(amount[i].ToString()));
                    //            priceTotal = amount[i] * float.Parse(price[i]);
                    //        }
                    //        else
                    //        {
                    //            weight[i] = float.Parse(ds.Tables[0].Rows[i]["Weight"].ToString());
                    //            numberInTable.Controls.Add(new LiteralControl(weight[i].ToString()));
                    //            priceTotal = weight[i] * float.Parse(price[i]);
                    //        }
                    //        Row.Cells.Add(numberInTable);
                    //        HtmlTableCell totalPrice = new HtmlTableCell();
                    //        totalPrice.Controls.Add(new LiteralControl(priceTotal.ToString()));
                    //        Row.Cells.Add(totalPrice);
                    //        dealTable.Rows.Add(Row);
                    //    }
                }
            }
        }

        //private void changeAddress(Object sender , EventArgs e)
        //{
        //    Button lb = sender as Button;
        //    Button bt = (Button)sender;
        //    string buttonId = lb.ID;
        //    int index = Convert.ToInt32(buttonId.Substring(buttonId.Length - 1, 1));//这样就可以知道第几个按钮被按下

        //    Page.ClientScript.RegisterStartupScript(this.GetType(), "dialog", "<script>fund("+index.ToString()+ ");</script>"));
        //    //Page.ClientScript.RegisterStartupScript(this.GetType(), "dialog", "<script>fund();</script>");
        //    //Page.ClientScript.RegisterStartupScript(this.GetType(), "dialog", script);
        //}
        protected void show()
        {
            SqlIt sql = new SqlIt();
            DataSet ds = new DataSet();
            string feild = "GoodsName,CartInfo.GoodsID,Price,CartInfo.Amount,CartInfo.Weight,PicturePath,SaleMethod";
            string table = "GoodsInfo,CartInfo";
            string condition = "CartInfo.UserID='" + userId + "' and CartInfo.GoodsID=GoodsInfo.ID";
            ds = sql.SpecialItem(table, condition, feild);
            BuildTable(ds);
        }
        private void BuildTable(DataSet ds)
        {
            int n = ds.Tables[0].Rows.Count;
            type = new string[n];
            //number = n;
            //定义表格头部
            HtmlTableRow tr = new HtmlTableRow();//定义行
            HtmlTableCell htd = new HtmlTableCell();//定义商品信息列
            Label lb1 = new Label();
            lb1.Text = "商品";
            htd.Controls.Add(lb1);
            htd.Width = "100";
            HtmlTableCell htd1 = new HtmlTableCell();//定义商品信息列
            Label lb2 = new Label();
            lb2.Text = "单价";
            htd1.Controls.Add(lb2);
            htd1.Width = "100";
            HtmlTableCell htdw = new HtmlTableCell();//定义商品信息列
            Label lbdw = new Label();
            lbdw.Text = "单位";
            htdw.Controls.Add(lbdw);
            htdw.Width = "150";
            HtmlTableCell htd2 = new HtmlTableCell();//定义商品信息列
            Label lb3 = new Label();
            lb3.Text = "数量/个数";
            htd2.Controls.Add(lb3);
            htd2.Width = "180";
            htd2.Align = "center";
            HtmlTableCell htd3 = new HtmlTableCell();//定义商品信息列
            Label lb4 = new Label();
            lb4.Text = "小计";
            htd3.Controls.Add(lb4);
            htd3.Width = "150";
            HtmlTableCell htd5 = new HtmlTableCell();//定义商品信息列
            htd5.Width = "150";
            tr.Cells.Add(htd5);
            tr.Cells.Add(htd);
            tr.Cells.Add(htd1);
            tr.Cells.Add(htdw);
            tr.Cells.Add(htd2);
            tr.Cells.Add(htd3);
            tr.BgColor = "#f7f7f7";
            tr.Attributes["class"] = "cart_inner";
            dealTable.Rows.Add(tr);
            if (n == 0)
            {
                HtmlTableRow trn = new HtmlTableRow();//定义行
                HtmlTableCell tdn = new HtmlTableCell();//定义商品信息列
                Label show = new Label();
                show.Text = "还没有选择商品哦~";
                tdn.Controls.Add(show);
                tdn.ColSpan = 3;
                trn.Cells.Add(tdn);
                dealTable.Rows.Add(trn);
            }
            else
            {
                for (int i = 0; i < n; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    type[i] = dr["SaleMethod"].ToString();
                    //if (judge==0)   //假设是论个数的
                    {
                        HtmlTableRow tr1 = new HtmlTableRow();//定义行
                        HtmlTableCell td1 = new HtmlTableCell();//定义商品信息列
                        Label goodsid = new Label();
                        goodsid.Text = "" + dr["GoodsID"];
                        goodsid.ID = "gid" + i;
                        goodsid.Visible = false;
                        Label salemethod = new Label();
                        salemethod.Text = "" + type[i];
                        salemethod.ID = "sm" + i;
                        salemethod.Visible = false;
                        ImageButton imageb = new ImageButton();      //图片
                        string path = "../images/" + dr["PicturePath"] + ".png";
                        imageb.Attributes["src"] = path;
                        imageb.Attributes["width"] = "50";
                        imageb.Attributes["height"] = "50";
                        imageb.ID = "imageb" + i;
                        td1.Controls.Add(goodsid);
                        td1.Controls.Add(salemethod);
                        td1.Controls.Add(imageb);
                        td1.Width = "140";
                        td1.Align = "center";
                        //td1.BgColor = "lightblue";
                        HtmlTableCell td2 = new HtmlTableCell();
                        LinkButton linkb = new LinkButton();         //商品名
                        linkb.Text = (string)dr["GoodsName"];
                        linkb.ID = "goodsname" + i;
                        td2.Controls.Add(linkb);
                        td2.Width = "140";
                        HtmlTableCell td3 = new HtmlTableCell();//定义列
                        Label lb = new Label();
                        string temp = dr["Price"].ToString();
                        lb.Text = "" + this.formatTrans(Double.Parse(temp));
                        lb.ID = "price" + i;
                        lb.Attributes["class"] = "singleprice";
                        td3.Controls.Add(lb);//列中添加txt1
                        td3.Width = "140";
                        HtmlTableCell htwd = new HtmlTableCell();//定义商品信息列
                        Label lbd = new Label();
                        if (type[i].Equals("0"))
                        {
                            lbd.Text = "/件";
                        }
                        else if (type[i].Equals("2"))
                        {
                            lbd.Text = "/千克";
                        }
                        else
                        {
                            lbd.Text = "/件";
                        }
                        lbd.Attributes["class"] = "singleprice";
                        htwd.Controls.Add(lbd);
                        htwd.Align = "left";
                        htwd.Width = "144";
                        HtmlTableCell td4 = new HtmlTableCell();
                        TextBox tb = new TextBox();
                        tb.ID = "amount" + i;
                        if (type[i].Equals("2"))  //散卖散算就读去重量
                        {
                            tb.Text = "" + dr["Weight"];
                        }
                        else
                        {
                            tb.Text = "" + dr["Amount"];
                        }
                        //个数
                        tb.Width = 50;
                        tb.ReadOnly = true;
                        //button1.Attributes["OnClick"] = "return add" + i + "()";
                        Label dw = new Label();
                        if (type[i].Equals("0"))
                        {
                            dw.Text = "件";
                        }
                        else if (type[i].Equals("1"))
                        {
                            dw.Text = "个";
                        }
                        else if (type[i].Equals("2"))
                        {
                            dw.Text = "千克";
                        }
                        else
                        {
                            dw.Text = "件";
                        }
                        dw.Attributes["class"] = "singleprice";
                        td4.Controls.Add(tb);
                        td4.Controls.Add(dw);
                        td4.Width = "140";
                        td4.Align = "center";
                        HtmlTableCell td5 = new HtmlTableCell();//定义列
                        Label suma = new Label();
                        double tp = 0;
                        if (type[i].Equals("1"))           //如果整卖散算则价格待定，需根据具体重量
                        {
                            suma.Text = "待定";
                            flag = 1;
                        }
                        else
                        {
                            tp = (Double.Parse(tb.Text) * Double.Parse(lb.Text));
                            suma.Text = "" + tp;   //小记价格
                            totalprice += tp;
                        }
                        suma.ID = "sum" + i;
                        td5.Controls.Add(suma);
                        td5.Width = "150";
                        td5.Attributes["class"] = "price";

                        tr1.Cells.Add(td1);//行中添加列td1
                        tr1.Cells.Add(td2);//行中添加列td1
                        tr1.Cells.Add(td3);
                        tr1.Cells.Add(htwd);
                        tr1.Cells.Add(td4);
                        tr1.Cells.Add(td5);
                        //tr1.BgColor = "PapayaWhip";
                        tr1.Attributes["class"] = "cart_body";
                        dealTable.Rows.Add(tr1);//表中添加行

                    }
                }

            }
            HtmlTableRow trt = new HtmlTableRow();//定义行
            HtmlTableCell tdt = new HtmlTableCell();//定义商品信息列
            Label total = new Label();
            total.Text = "合计：￥ ";
            //.ID = "tp";
            total.Attributes["class"] = "tail1";
            tdt.Controls.Add(total);
            tdt.ColSpan = 5;
            tdt.Align = "right";
            HtmlTableCell tdp = new HtmlTableCell();//定义商品信息列
            Label g = new Label();
            g.Text = totalprice + "";
            g.CssClass = "tail2";
            Label dd = new Label();
            if (flag == 0)
            {
                dd.Text = "";
            }
            else
            {
                dd.Text = "+待定";
            }
            dd.CssClass = "tail2";
            dd.ID = "daiding";
            tdt.Controls.Add(g);
            tdt.Controls.Add(dd);
            HtmlTableCell tdb = new HtmlTableCell();
            //Button b = new Button();
            //b.Text = "结算";
            //b.CssClass = "submit_button";
            //tdb.Controls.Add(b);
            trt.Cells.Add(tdt);
            trt.Cells.Add(tdp);
            trt.Cells.Add(tdb);
            // trt.BgColor = "lightgrey";
            trt.Attributes["class"] = "cart_body";
            dealTable.Rows.Add(trt);
        }
        private void r_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rad = sender as RadioButton;
            string buttonid = rad.ID;
            radioId = Convert.ToInt32(rad.ID.Substring(buttonid.Length - 1, 1));
        }
        public double formatTrans(double n)
        {
            double r = 0;
            r = Math.Floor(100 * n) * 1.0 / 100.0;
            return r;
        }

        protected void submitOrder_Click(object sender, EventArgs e)
        {
            SqlIt sql = new SqlIt();
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //string status = "0";
            string _remark = remark.Text.ToString();
            //int addrNum = 0;
            DataSet addrNumDs = sql.SpecialItem("DeliveryInfo", "UserID=" + userId, "ID");
            string addrNum = addrNumDs.Tables[0].Rows[radioId][0].ToString();
            //for (int i = 0; i < addrNum; i++)
            //{
            //    //if
            //}
            //添加订单信息表
            Dictionary<string, string> dc = new Dictionary<string, string>();
            dc.Add("UserID", userId.ToString());
            dc.Add("Time", date);
            dc.Add("Status", "1");
            dc.Add("Remark", _remark);
            dc.Add("Delivery", addrNum);
            sql.AddMess("OrderInfo", dc);

            //添加订单详情表
            string id = sql.SingleSpecialItem("OrderInfo", "UserID= " + userId.ToString() + " and CONVERT(varchar(100), Time, 120) like '" + date + "'", "ID").ToString();
            DataSet ds = sql.SpecialItem("CartInfo", "UserID =" + userId, "*");
            int goodsNum = ds.Tables[0].Rows.Count;

            String goodsId = null;
            //type = new string[goodsNum];
            string typeGoods;
            string price;//单价
            int amount;//数量
            double weight;//重量
            for (int i = 0; i < goodsNum; i++)
            {
                goodsId = ds.Tables[0].Rows[i]["GoodsID"].ToString();
                typeGoods = sql.SingleSpecialItem("GoodsInfo", "ID=" + goodsId, "SaleMethod").ToString();
                Dictionary<string, string> addDetail = new Dictionary<string, string>();
                addDetail.Add("OrderID", id);
                addDetail.Add("GoodsID", goodsId);
                if (typeGoods.Equals("0") || typeGoods.Equals("1"))
                {
                    amount = (int)ds.Tables[0].Rows[i]["Amount"];
                    addDetail.Add("Amount", amount.ToString());
                }
                else
                {
                    weight = Convert.ToDouble(ds.Tables[0].Rows[i]["Weight"]);
                    addDetail.Add("Weight", weight.ToString());
                }
                price = sql.SingleSpecialItem("GoodsInfo", "ID=" + goodsId, "Price").ToString();
                addDetail.Add("Price", price);
                sql.AddMess("OrderDetail", addDetail);
            }

            //删除购物车内容
            sql.SpecialDelete("CartInfo", "UserID=" + userId.ToString());

            Response.Redirect("./FinishOrder.aspx");
        }
    }

}